package com.huang.foundation.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.huang.foundation.entity.to.AliYunOSSDTO;
import com.huang.foundation.entity.to.AliYunSTSDTO;
import com.huang.foundation.properties.AliYunProperties;
import com.huang.foundation.service.AliYunSTSService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author HuangShen
 * @Description
 * @create 2021-10-13 22:55
 */
@Service("aliYunSTSService")
public class AliYunSTSServiceImpl implements AliYunSTSService {
    @Resource
    private AliYunProperties aliYunProperties;
    private static final Logger logger = LoggerFactory.getLogger(AliYunSTSServiceImpl.class);


    @Override
    public AliYunSTSDTO getToken(String project) {

        //构建一个阿里云客户端，用于发起请求。
        //构建阿里云客户端时需要设置AccessKey ID和AccessKey Secret。
        DefaultProfile profile = DefaultProfile.getProfile(aliYunProperties.getRegionId(), aliYunProperties.getAccessKeyId(), aliYunProperties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        //构造请求，设置参数。关于参数含义和设置方法，请参见API参考。
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleArn(aliYunProperties.getRoleArn());
        request.setRoleSessionName(project);
        request.setDurationSeconds(aliYunProperties.getDurationSeconds());

        //发起请求，并得到响应。
        try {
            AssumeRoleResponse response = client.getAcsResponse(request);
            AssumeRoleResponse.Credentials credentials = response.getCredentials();
            AssumeRoleResponse.AssumedRoleUser assumedRoleUser = response.getAssumedRoleUser();
            return AliYunSTSDTO.builder()
                    .accessKeyId(credentials.getAccessKeyId())
                    .accessKeySecret(credentials.getAccessKeySecret())
                    .expiration(credentials.getExpiration())
                    .securityToken(credentials.getSecurityToken())
                    .arn(assumedRoleUser.getArn())
                    .assumedRoleId(assumedRoleUser.getAssumedRoleId()).build();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            logger.error("获取阿里云OSS 临时token 错误 ErrCode：{},ErrMsg:{},RequestId:{}", e.getErrCode(), e.getErrMsg(), e.getRequestId());
        }

        return null;
    }

    @Override
    public AliYunOSSDTO getOSSToken(String type, String project) {

        AliYunSTSDTO aliYunSTSDTO = this.getToken(project);
        String callbackUrl = "";
        return AliYunOSSDTO.builder()
                .accessKeyId(aliYunSTSDTO.getAccessKeyId())
                .accessKeySecret(aliYunSTSDTO.getAccessKeySecret())
                .expiration(aliYunSTSDTO.getExpiration())
                .securityToken(aliYunSTSDTO.getSecurityToken())
                .arn(aliYunSTSDTO.getArn())
                .assumedRoleId(aliYunSTSDTO.getAssumedRoleId())
                .bucket(aliYunProperties.getBucket())
                .callbackUrl(callbackUrl)
                .host("")
                .region(aliYunProperties.getRegionId())
                .build();
    }

    @Override
    public boolean deleteFile(String filePath) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint =aliYunProperties.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = aliYunProperties.getAccessKeyId();
        String accessKeySecret = aliYunProperties.getAccessKeySecret();
        // 填写Bucket名称。
        String bucketName = aliYunProperties.getBucket();
        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 删除文件或目录。如果要删除目录，目录必须为空。
        try {
            ossClient.deleteObject(bucketName, filePath);
        }catch (Exception e){
            return false;
        }finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        return true;
    }
}
